<template>
  <div class="contentRight2">
    <div id="tools">

      <div class="height8"></div>
      <!-- 查询条件 -->
      <a-form layout="inline" style="text-align: left;padding: 0 10px;" :selfUpdate="true">

        <!--<a-form-item label="开始日期" class="marginBtm">-->
          <!--<a-date-picker-->
            <!--:disabledDate="disabledStartDate"-->
            <!--v-model="startDate"-->
            <!--placeholder="开始日期"-->
            <!--show-time-->
            <!--style="width: 180px;"-->
            <!--@openChange="handleStartOpenChange"-->
          <!--/>-->
        <!--</a-form-item>-->
        <!--<a-form-item label="结束日期" class="marginBtm">-->
          <!--<a-date-picker-->
            <!--:disabledDate="disabledEndDate"-->
            <!--placeholder="结束日期"-->
            <!--show-time-->
            <!--v-model="endDate"-->
            <!--:open="endOpen"-->
            <!--style="width: 180px;"-->
            <!--@openChange="handleEndOpenChange"-->
          <!--/>-->
        <!--</a-form-item>-->

        <!--<a-form-item label="基地" class="marginBtm">-->
          <!--<a-dropdown class="min-width-110">-->
            <!--<a-menu slot="overlay" @click="baseMenuClick">-->
              <!--<a-menu-item :key="item.id" v-for="item in baceType">{{item.name}}</a-menu-item>-->
            <!--</a-menu>-->
            <!--<a-button>-->
              <!--<div class="query-conditions">-->
                <!--{{ visitBaseName }}-->
                <!--<a-icon type="down"/>-->
              <!--</div>-->
            <!--</a-button>-->
          <!--</a-dropdown>-->
        <!--</a-form-item>-->

        <!--<a-form-item label="区域" class="marginBtm">-->
          <!--<a-dropdown class="min-width-110">-->
            <!--<a-menu slot="overlay" @click="areaMenuClick">-->
              <!--<a-menu-item :key="item.id" v-for="item in areaList">{{item.areaName}}</a-menu-item>-->
            <!--</a-menu>-->
            <!--<a-button>-->
              <!--<div class="query-conditions">-->
                <!--{{ areaName }}-->
                <!--<a-icon type="down"/>-->
              <!--</div>-->
            <!--</a-button>-->
          <!--</a-dropdown>-->
        <!--</a-form-item>-->

        <!--<a-form-item label="门" class="marginBtm">-->
          <!--<a-dropdown class="min-width-110">-->
            <!--<a-menu slot="overlay" @click="doorMenuClick">-->
              <!--<a-menu-item :key="item.typeId" v-for="item in doorList">{{item.name}}</a-menu-item>-->
            <!--</a-menu>-->
            <!--<a-button>-->
              <!--<div class="query-conditions">-->
                <!--{{ doorName }}-->
                <!--<a-icon type="down"/>-->
              <!--</div>-->
            <!--</a-button>-->
          <!--</a-dropdown>-->
        <!--</a-form-item>-->


        <a-form-item label="关键字" class="marginBtm">
          <a-input
            v-model="queryValue"
            allowClear
            placeholder="请输入姓名/工号"
            class="marginBtm"
            @pressEnter="inquireStart"
          />
        </a-form-item>

        <a-form-item class="marginBtm">
          <a-button type="primary" @click="inquireStart">
            查询
          </a-button>
        </a-form-item>

      </a-form>
      <a-divider style="margin: 5px 0"/>
      <div class="divPadiAlign" v-if="isSuper == '是'">
        <!--<a-button type="primary" class="button-marin" @click="exportList">-->
          <!--导出-->
        <!--</a-button>-->

        <a-button  type="primary" class="button-marin" @click="addPeopleModalShow">
          新增
        </a-button>
        <a-button  type="primary" class="button-marin" @click="dateleUser">
          删除
        </a-button>
      </div>
    </div>

    <a-table
      class="tabled"
      bordered
      :fixed="true"
      size="small"
      :columns="columns"
      :row-key="record => record.id"
      :data-source="tableData"
      :pagination="pagination"
      :loading="loading"
      :scroll="{ x:xWidth,y: yHeight }"
      :locale="localezh_CN"
      @change="handleTableChange"
      :customRow="clickRow"
      :rowSelection="{selectedRowKeys:selectedRowKeys,fixed:true,onChange:onChangeSelectedRow}"
    >
      <!--设置单选按钮-->
      <!--:rowSelection="{type:'radio'}"-->
    </a-table>

    <!--添加人员-->
    <a-modal
      v-model="addPeopleModal"
      :destroyOnClose="true"
      :maskClosable="false"
      :keyboard="false"
      :title="addPeopleTitle"
      @ok="addPeoplehandleOk"
      @cancel="addPeopleCancel"
      :bodyStyle="{padding: '10px 10px 30px 10px'}"
      width="620px"
    >
      <a-spin :spinning="addPeopleSpinning">
        <a-descriptions bordered size="small" :column="4">
          <a-descriptions-item :span="2">
            <template v-slot:label>
              <div class="contShortwidth">工号</div>
            </template>
            <div class="contwidthLon">
              <a-input-search placeholder="请输入工号" @search="onSearchByUserNo"
                              v-model="addPeopleParam.userNo">
                <a-button type="primary" slot="enterButton">
                  查询
                </a-button>
              </a-input-search>
            </div>
          </a-descriptions-item>
          <a-descriptions-item :span="2">
            <template v-slot:label>
              <div class="contShortwidth">姓名</div>
            </template>
            <div class="contwidthLon">
              <a-input placeholder="请输入姓名" disabled v-model="addPeopleParam.userName"/>
            </div>
          </a-descriptions-item>
          <!--<a-descriptions-item :span="2">-->
            <!--<template v-slot:label>-->
              <!--<div class="contShortwidth">英文名</div>-->
            <!--</template>-->
            <!--<div class="contwidthLon">-->
              <!--<a-input placeholder="请输入英文名" disabled v-model="addPeopleParam.userNameEn"/>-->
            <!--</div>-->
          <!--</a-descriptions-item>-->
          <a-descriptions-item :span="4">
            <template v-slot:label>
              <div class="contShortwidth">部门</div>
            </template>
            <div class="contwidthLon">
              <a-input placeholder="请输入部门" disabled v-model="addPeopleParam.deptName"/>
            </div>
          </a-descriptions-item>

          </a-descriptions>

      </a-spin>

    </a-modal>
    <!--导出加载中-->
    <customLoading :customVisible="spinning"></customLoading>

    <!--设备目录-->
    <a-modal
      v-model="photoVisible"
      title="查看图片"
      width="1100px"
      :destroyOnClose="true"
      :maskClosable="false"
      :keyboard="false">
      <template slot="footer">
        <a-button key="submit" type="primary" @click="savephoto">
          保存图片
        </a-button>
        <a-button key="back" @click="handleCancel">
          关闭
        </a-button>
      </template>
      <a-spin :spinning="photoSpinning">
        <div style="width: 100%;height: 66vh;overflow: auto">
          <img v-for="item in lookImg " :src="item" alt="" style="width: 320px;margin:0 20px 20px 0;object-fit: cover;">
        </div>
      </a-spin>

    </a-modal>

  </div>
</template>

<script>
  import {tableBoxHeight} from "@/api/communal";
  import reservationApi from "@/api/reservation";
  import adminsDefinitionApi from "@/api/visitorSystem/adminsDefinition";
  import forgotCardManageApi from "@/api/forgotCardManage";
  import localezh_CN from 'antd/lib/locale-provider/zh_CN';
  import moment from "moment";
  import {ConfigProvider} from 'ant-design-vue';//引用
  import 'moment/locale/zh-cn';
  import cfg from '@/config/config'

  export default {
    components: {
      ConfigProvider
    },
    name: '',
    data() {
      return {
        localezh_CN,
        spinning: false,
        isSuper:"",  //是否是超级管理员
        xWidth: "1200px",
        yHeight: "",
        tableData: [],
        pagination: {
          pageSize: 30,
          current: 1,
          total: 0,
          showSizeChanger: true,
          // showQuickJumper: true,
          pageSizeOptions: ["20", "30", "50"],
          showTotal: (total) => `共 ${total} 条`, // 显示总数
          onShowSizeChange: (current, pageSize) => {
            // console.log("1111");
            this.pagination.current = 1;
            this.pagination.pageSize = pageSize;
          },
        },
        selectedRowKeys: [],
        selectedRow: [],
        loading: false,
        dateFormat: 'YYYY/MM/DD',
        startDate: "",
        endDate: "",
        endOpen: false,
        startDated: "",
        endDated: "",
        queryValue: "",  //查询值,访客名称，访客手机号
        columns: [],   //表格表头
        addPeopleModal: false,  //添加人员弹窗
        addPeopleSpinning: false,
        addPeopleTitle: "添加人员",
        addPeopleParam:{
          id: "",
          userSerial:"",
          userNo:"",
          userName:"",   //中文名
          userNameEn:"",   //英文名
          remark:"",       //备注
          deptName:"",   //部门
        },

        visibleModal: false,  //新增修改弹窗
        visibleTitle:"新增",  //动态title
        modalSpinning: false, //弹窗加载
        photoVisible: false,
        photoSpinning: false,
        lookImg: [],
        //基地列表
        visitBaseName: "全部",   //基地名称
        visitBaseId: 99,   //99查全部，或者基地id
        baceType: [
          {name: "全部", id: 99},
        ],
        baceTypeModal:[],   //弹窗基地名称
        //区域列表
        areaName: "全部",    //区域名称
        visitAreaId: "",   //99查全部，或者区域id
        isHaveDoor: 0,   //是否有门 1有门 ， 0 没有门
        areaList: [
          {areaName: "全部", id: ""},
        ],
        areaListModal:[], //弹窗区域列表
        //门列表
        doorName: "全部",    //区域名称
        doorId: "",   //门id
        doorList: [
          {name: "全部", typeId: ""},
        ],

      }
    },
    beforeMount() {
      this.columns = [
        {
          title: '序号',     //表头
          dataIndex: 'serialNumber',   //字段名称
          width: '50px',    //设列宽度
          align: 'center',  //居中显示
          fixed: "left",
          className: 'changeBack',   //重置覆盖背景色为浅灰色，否则是白色的
          customRender: (value, row, index) => `${(this.pagination.current - 1) * this.pagination.pageSize + index + 1}`  //设置动态序号
        },
        {
          title: '工号',
          dataIndex: 'personalNumber',
          width: '100px',
          align: 'center',
          ellipsis: true,
          className: 'changeBack'
        },
        {
          title: '姓名',
          dataIndex: 'chineseName',
          width: '100px',
          align: 'center',
          ellipsis: true,
          className: 'changeBack'
        },
        {
          title: '部门',
          dataIndex: 'orgunitShort',
          width: '120px',
          align: 'center',
          ellipsis: true,
          className: 'changeBack'
        },
        {
          title: '添加人',
          dataIndex: 'createByName',
          width: '100px',
          align: 'center',
          ellipsis: true,
          className: 'changeBack'
        },
        {
          title: '添加时间',
          dataIndex: 'createTime',
          width: '150px',
          align: 'center',
          ellipsis: true,
          className: 'changeBack'
        },
        {
          title: '',
          dataIndex: '',
          width: 'auto',
          align: 'center',
          className: 'changeBack'
        },
        // {
        //   title: '操作',
        //   dataIndex: 'operate',
        //   key: 'operate',
        //   width: '120px',
        //   scopedSlots: {customRender: 'operate'},
        //   fixed: "right",
        //   align: "center",
        //   className: "changeBack"
        // },

      ];

      // this.startDate = moment().startOf('month');
      // this.endDate = moment().endOf('month');
      // this.startDated = moment(this.startDate).format('YYYY-MM-DD HH:mm:ss');
      // this.endDated = moment(this.endDate).format('YYYY-MM-DD HH:mm:ss');
      this.checkIsSuper();
    },
    async mounted() {
      // this.xWidth = this.getTableWidth();
       this.inquireStart();

    },
    methods: {
      //查询登陆人是否是超级管理员
      checkIsSuper() {
        adminsDefinitionApi.checkIsSuper().then(res=>{
          // console.log(res);
          if (res.data.success) {
            this.isSuper = res.data.result.isSuper;
          } else {
            this.$message.error(res.data.message);
          }
        })
      },
      // 计算表格宽度
      getTableWidth() {
        let totals = null;
        var el;
        for (el of this.columns) {
          totals += parseInt(el.width);
        }
        return totals + 100 + "px"
      },
      // 选择日期
      onChangePicker(date, dateString) {
        // console.log(date, dateString);
        this.startDated = dateString[0];
        this.endDated = dateString[1];
      },
      //日期控件需要的方法
      disabledStartDate(startDate) {
        const endDate = this.endDate;
        if (!startDate || !endDate) {
          return false;
        }
        return startDate.valueOf() > endDate.valueOf();
      },
      disabledEndDate(endDate) {
        const startDate = this.startDate;
        if (!endDate || !startDate) {
          return false;
        }
        return startDate.valueOf() >= endDate.valueOf();
      },
      handleStartOpenChange(open) {
        // if (!open) {
        //   this.endOpen = true;
        // }
      },
      handleEndOpenChange(open) {
        this.endOpen = open;
      },

      // 导出列表
      async exportList() {
        this.startDated = this.startDate == "" || this.startDate == null ? "" : moment(this.startDate).format('YYYY-MM-DD HH:mm:ss');
        this.endDated = this.endDated == "" || this.endDated == null ? "" : moment(this.endDate).format('YYYY-MM-DD HH:mm:ss');
        if (this.startDated == "") {
          this.$message.warning("开始日期不能为空");
          return
        }
        if (this.endDated == "") {
          this.$message.warning("结束日期不能为空");
          return
        }
        this.spinning = true;
        let param = {
          current: this.pagination.current,
          pageSize: this.pagination.pageSize,
          // startDate: this.startDated,
          // endDate: this.endDated,
          // serchTxt: this.queryValue,
          baseId: this.visitBaseId,
          areaId: this.visitAreaId == "" ? 99 : this.visitAreaId,

        };
        let jsonIn = encodeURI(encodeURI(JSON.stringify(param)));
        await window.open(cfg.apiUrl + 'api/visitor/exportVisitList?jsonIn=' + jsonIn, "_self");
        setTimeout(() => {
          this.spinning = false;
        }, 1000)

      },
      // 开始查询
      inquireStart() {
        this.pagination.current = 1;
        let param = {
          current: this.pagination.current,
          pageSize: this.pagination.pageSize,
          searchTxt: this.queryValue
          // baseId: this.visitBaseId,   //99查全部，或者基地id
          // areaId: this.visitAreaId == "" ? 99 : this.visitAreaId,   //99查全部，或者区域id
        };

        this.fetch(param);
      },

      // 切换基地，选择基地
      baseMenuClick(e) {
        // console.log(e);
        this.baceType.filter(el => {
          if (el.id == e.key) {
            // console.log(el);
            this.visitBaseName = el.name;
            this.visitBaseId = el.id;
            this.areaName = "全部";
            this.visitAreaId = "";
            this.isHaveDoor = 0;
            // this.doorName = "全部";
            // this.doorId = "";
            // this.doorList = [{name: "全部", id: ""}];
            if (el.id == 99) {
              this.areaList = [{areaName: "全部", id: 99}];
              // this.getVisitorType()
            } else {
              this.getAreaList(1)
            }
          }
        });

      },
      // 切换区域，选择区域
      areaMenuClick(e) {
        // console.log(e);
        this.areaList.filter(el => {
          if (el.id == e.key) {
            // console.log(el);
            this.areaName = el.areaName;
            this.visitAreaId = el.id;
          }
        });
      },
      // 切换门，选择门
      doorMenuClick(e) {
        // console.log(e);
        this.doorList.filter(el => {
          if (el.typeId == e.key) {
            // console.log(el);
            this.doorName = el.name;
            this.doorId = el.typeId;
            // this.getVisitorType();
          }
        });
      },

      // 点击行
      clickRow(record) {
        return {
          on: {
            click: () => {
              // 单选
              // let keys = [];
              // keys.push(record.id);
              // this.selectedRowKeys = keys;
              // this.selectedRow = record;

              //多选
              if (this.selectedRowKeys.indexOf(record.id) > -1) {
                this.selectedRow = this.selectedRow.filter(v => {
                  return v.id != record.id
                })
                this.selectedRowKeys.splice(this.selectedRowKeys.indexOf(record.id), 1)
              } else {
                this.selectedRow.push(record)
                this.selectedRowKeys.push(record.id)
              }
            }
          }
        }
      },
      seePhoto(row) {
        // console.log(row);
        this.lookImg = [];
        this.photoSpinning = true;
        this.photoVisible = true;
        this.getPhotoList(row.orderId);
      },
      // 获取图片
      async getPhotoList(id) {
        let resp = await reservationApi.getAttachmentNameList({orderId: id});
        // console.log(resp.data);
        if (resp.data.success) {
          this.lookImg = resp.data.result;
          this.photoSpinning = false;
        } else {
          this.photoSpinning = false;
          this.$message.error(resp.data.message);
        }
      },
      // 获取基地信息
      async findRegionList() {
        let resp = await reservationApi.getBdSysItemList({typeId: 200});
        // console.log(resp);
        if (resp.data.success) {
          this.baceType = [...this.baceType, ...resp.data.result];
          this.baceTypeModal = resp.data.result;
          // console.log(this.baceType)
        } else {
          this.$message.error(resp.data.message);
        }
      },
      // 获取区域
      async getAreaList(num) {
        // console.log(num)
        // num 1 主页面的请求 2弹窗的请求
        let res = await reservationApi.getVisitorTypeAreaList({typeId: this.visitBaseId})
        // console.log(res.data);
        if (res.data.success) {
          if (num == 1) {
            this.areaList = [{areaName: "全部", id: ""}];
            this.areaList = [...this.areaList, ...res.data.result];
          } else {
            this.areaListModal = res.data.result;
          }
        } else {
          this.$message.error(res.data.message);
        }
      },
      // 获取门列表
      async getDoorList() {
        // console.log("区域id："+this.visitAreaId);
        let res = await reservationApi.getSysItemByArea({areaId: ""})
        // console.log(res.data);
        if (res.data.success) {
          this.doorList = [{name: "全部", typeId: ""}];
          this.doorList = [...this.doorList, ...res.data.result];
          // this.doorName = res.data.result[0].name;
          // this.doorId = res.data.result[0].typeId;
          // console.log(this.doorList)
        } else {
          this.$message.error(res.data.message);
        }
      },

      // 表格切换分页
      handleTableChange(pagination, filters, sorter) {
        const pager = {...this.pagination};
        pager.current = pagination.current;
        this.pagination = pager;
        this.fetch({
          pageSize: pagination.pageSize,
          current: pagination.current,
          searchTxt: this.queryValue,
          // baseId: this.visitBaseId,   //99查全部，或者基地id
          // areaId: this.visitAreaId == "" ? 99 : this.visitAreaId,   //99查全部，或者区域id
          sortField: sorter.field,
          sortOrder: sorter.order,
          ...filters,
        });
      },

      //删除黑名单人员
      dateleUser() {
        let _this = this;
        if (this.selectedRowKeys.length == 0) {
          this.$message.warning("请选择要删除的人员");
          return
        } else {
          this.$confirm({
            title: '删除确认',
            content: '确定要删除已选择的人员吗？',
            okText: '确认',
            cancelText: '取消',
            onOk() {
              //删除
              let param = {
                blackIds: _this.selectedRowKeys.join()
              }
              _this.loading = true
              forgotCardManageApi.delBlackEmpInfo(param).then(res => {
                _this.loading = false
                if (res.data.success) {
                  _this.$message.success(res.data.message);
                  _this.inquireStart();
                } else {
                  _this.$message.error(res.data.message);
                }
              })
            },
          });
        }
      },

      handleCancel() {
        this.photoVisible = false
      },

      savephoto() {
        let length = this.lookImg.length;
        for (let i = 0; i < length; i++) {
          let createA = document.createElement("a");
          let src = this.lookImg[i];
          createA.id = "img_" + i;
          createA.href = src;
          createA.download = src;
          createA.target = "_blank";
          // console.log(createA);
          document.body.appendChild(createA);
        }
        for (let j = 0; j < length; j++) {
          if (document.getElementById("img_" + j)) {
            //重点：触发a标签的click事件，触发事件后移除该图片元素标签
            document.getElementById("img_" + j).click();
            document.body.removeChild(document.getElementById("img_" + j));
          }
        }
      },

      onChangeSelectedRow(selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys;
        this.selectedRow = selectedRows;
      },
      // 请求表格数据
      async fetch(params) {
        this.loading = true;
        let resp = await forgotCardManageApi.getBlackEmpList(params);
        // console.log(resp.data);
        if (resp.data.success) {
          this.loading = false;
          this.pagination.total = resp.data.result.total;
          this.tableData = resp.data.result.records;
          this.$nextTick(()=>{
            this.yHeight = tableBoxHeight() + 3 + "px";
            let minHeight = document.getElementsByClassName("ant-table");
            minHeight[0].style.minHeight = tableBoxHeight() + 40 + "px";
          })
        } else {
          this.loading = false;
          this.$message.error(resp.data.message);
        }

        // 测试
        // setTimeout(() => {
        //   this.tableData=[
        //     {
        //       //   id: 1,
        //   baseName:"安亭基地",
        //   areaNames:"办公区域",
        //   ifTwoApprove: 0,
        //   twoApproveBegin: "2020-10-10 08:00:00",
        //   twoApproveEnd: "2020-10-10 17:30:00",
        //   ifThreeApprove: 1,
        //   threeApproveBegin: "2020-10-10 08:00:00",
        //   threeApproveEnd: "2020-10-10 17:30:00",
        //   ifFourApprove: 1,
        //   fourApproveBegin: "2020-10-10 08:00:00",
        //   fourApproveEnd: "2020-10-10 17:30:00",
        //   createTime: "2020-10-10 08:00:00",
        //   createPeople: "admin"
        //     },
        //   ];
        //   this.tableData=this.tableData.map((el,i)=>{
        //      el.id = i + 1;
        //      return el
        //   });
        //   console.log(this.tableData);
        //     this.loading = false;
        //   }, 2000);

      },

      addPeopleModalShow() {
        this.addPeopleModal = true;
      },
      // 新增保存
      async addPeoplehandleOk() {
        if (this.addPeopleParam.userNo.trim() == "") {
          this.$message.warning("工号不能为空");
          return
        }

        let res = await forgotCardManageApi.addBlackEmpInfo({
          personalNumber: this.addPeopleParam.userNo,
          chineseName: this.addPeopleParam.userName,
          orgunitShort: this.addPeopleParam.deptName
        })
        // console.log(res.data);
        if (res.data.success) {
          this.$message.success(res.data.message);
          this.visibleModal = false;
          this.addPeopleCancel();
          this.inquireStart();
        } else {
          this.$message.error(res.data.message);
        }

        // this.addPeopleCancel();
      },
      addPeopleCancel() {
        this.addPeopleParam = {
          userSerial: "",
          userNo: "",
          userName: "",
          userNameEn: "",
          remark: "",
          deptName:""
        };
        this.addPeopleSpinning = false;
        this.addPeopleModal = false;
      },
      async onSearchByUserNo() {
        let reg = /^[A-Za-z0-9]+$/; //包含数字字母，不包含特殊字符

        if (this.addPeopleParam.userNo.trim() == "") return;
        if(reg.test(this.addPeopleParam.userNo)){
          // console.log("正确");
        }else{
          // console.log("错误");
          this.$message.warning("请输入正确的工号");
          return
        }

        this.addPeopleSpinning = true;
        let resp = await forgotCardManageApi.getBlackEmpInfo(this.addPeopleParam.userNo.trim());
        // console.log(resp.data);
        if (resp.data.success) {
          this.addPeopleSpinning = false;
          if (resp.data.result == null) {
            this.$message.error("未查询到员工信息");
          } else {
            this.addPeopleParam = {
              userNo: resp.data.result.personalNumber,
              userName: resp.data.result.chineseName,
              deptName: resp.data.result.orgunitShort
            };
          }

        } else {
          this.addPeopleSpinning = false;
          this.$message.error(resp.data.message);
        }
      },

    }
  }
</script>

<style scoped>


</style>

